package com.zhongwang.business.module.system.user;


import com.zhongwang.business.base.BaseService;
import com.zhongwang.business.gen.entity.User;
import com.zhongwang.business.gen.mapper.UserMapper;
import com.zhongwang.business.module.system.dept.DeptMapper;
import com.zhongwang.business.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Base64;
import java.util.List;

import static com.zhongwang.business.constant.Constant.STATUS_NORMAL;
import static com.zhongwang.business.util.BeanUtil.copy;


/**
 *  用户 服务层
 *
 * @author China.sgl
 * @date 2019/9/16 09:11
 */
@Service
public class UserService extends BaseService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DeptMapper deptMapper;

    /**
     * 根据条件查询用户
     *
     * @param user 查询条件
     * @return 用户表数据
     */
    public List<User> findAll(User user){
        return userDao.findAll(user);
    }

    /**
     * 按帐号查询用户
     *
     * @param account 帐号
     * @return 用户数据
     */
    public User findByAccount(String account){
        return userDao.findByAccount(account);
    }

    /**
     * 修改帐户
     *
     * @param user 帐户对象
     * @return 影响行数
     */
    public int updateUser(User user) {
        logService.saveLog("修改帐户","");
        return userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 重置密码
     *
     * @param id 帐户 ID
     * @return 影响行数
     */
    public int resetPassword(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        Object obj = new SimpleHash("MD5", "111111", ByteSource.Util.bytes(user.getAccount()), 8);
        user.setPassword(obj.toString());
        logService.saveLog("重置密码","");
        return updateUser(user);
    }

    public int resetPassword2(Integer id) {
        User user = userMapper.selectById(id);
        Object obj = new SimpleHash("MD5", "111111", ByteSource.Util.bytes(user.getAccount()), 8);
        user.setPassword(obj.toString());
        logService.saveLog("重置密码","");
        return updateUser(user);
    }

    /**
     * 保存帐户及帐户拥有角色
     *
     * @param user 帐户信息
     * @param roleIds 角色 ID 数组
     * @return 影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveUser(User user, Integer[] roleIds) {
        Object obj = new SimpleHash("MD5", user.getPassword(), ByteSource.Util.bytes(user.getAccount()), 8);
//        Object ttt = new SimpleHash("MD5", "111111", ByteSource.Util.bytes("admin"), 8);
        user.setPassword(obj.toString());
        user.setStatus(STATUS_NORMAL);
        int row = userMapper.insert(user);
        if (roleIds.length > 0) {
            userDao.batchInsertUserRoles(user.getId(), roleIds);
            logService.saveLog("保存帐户及帐户拥有角色","");
        }
        return row;
    }

    /**
     * 修改帐户及拥有角色
     *
     * @param user 帐户信息
     * @param roleIds 拥有角色ID
     * @return 影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(User user, Integer[] roleIds) {
        int row = userMapper.updateByPrimaryKeySelective(user);
        userDao.deleteUserRoleByUserId(user.getId());
        if (roleIds.length > 0) {
            userDao.batchInsertUserRoles(user.getId(), roleIds);
            logService.saveLog("修改帐户及拥有角色","");
        }
        return row;
    }

    /**
     * 修改密码
     *
     * @param password 密码
     * @return 影响行数
     */
    public int updatePassword(String password) {
        Session session = SecurityUtils.getSubject().getSession();
        User user = (User) session.getAttribute("user");
        int hashIterations = 8;
        Object obj = new SimpleHash("MD5", password, ByteSource.Util.bytes(user.getAccount()), hashIterations);
        user.setPassword(obj.toString());
        logService.saveLog("修改密码","");
        return updateUser(user);
    }

    /**
     * 根据ID查询用户
     *
     * @param id 用户ID
     * @return 用户
     */
    public User findUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 修改密码
     *
     * @param password 密码
     * @return 行数
     */
    public int updateUserPassword(String password) {
        User user = ShiroUtils.getUser();
        int hashIterations = 8;
        Object obj = new SimpleHash("MD5", password, ByteSource.Util.bytes(user.getAccount()), hashIterations);
        user.setPassword(obj.toString());
        logService.saveLog("修改密码","");
        return userMapper.updateByPrimaryKey(user);
    }

    /**
     * 获取用户未读消息
     *
     * @param type 消息类型
     * @return list
     */
//    public List<MessageModel> findMessageByType(Integer type) {
//        return userDao.findMessageByUserId(ShiroUtils.getUserId(), type);
//    }

    /**
     * 上传头像
     *
     * @param s 头像路径
     */
    public User updateImage(String s,String imageData) {
        User saveUser = new User();
        saveUser.setId(ShiroUtils.getUserId());
        saveUser.setImg(s);
        String base64 = imageData.substring(imageData.indexOf(",") + 1);
        byte[] decoderBytes = Base64.getDecoder().decode(base64);
        saveUser.setImgBlob(decoderBytes);
        userMapper.updateByPrimaryKeySelective(saveUser);
        saveUser = userMapper.selectByPrimaryKey(ShiroUtils.getUserId());
        ShiroUtils.getSubject().getSession().setAttribute("user", saveUser);
        logService.saveLog("修改头像","");
        return saveUser;
    }
    /**
     * 修改帐户及拥有角色
     *
     * @param user    帐户信息
     * @param roleIds 拥有角色ID
     * @param orgId 拥有部门ID
     * @return 影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    public User updateUser(User user, Integer[] roleIds, Integer orgId, Integer deptId) {
        Integer dept = null;
        if (deptId != null) {
            dept = deptMapper.findTopLevelDept(deptId);
        }
        User u = userMapper.selectById(user.getId());
        u.setOrgId(orgId);
        u.setDeptId(deptId);
        u.setDept(dept);
        copy(user, u);
        userMapper.updateByPrimaryKey(u);
        userMapper.deleteUserRoleByUserId(user.getId());
        if (roleIds.length > 0) {
            userMapper.batchInsertUserRole(u.getId(), roleIds);
            logService.saveLog("修改用户",u.getName());
        }
        return u;
    }
}
